// src/hooks/useThemeMode.ts
import { computed, onMounted, watch } from "vue";
import { useGlobalStore } from "@/stores/modules/global"; // 导入 ThemeMode 类型
import { updateElementPlusTheme } from "@/utils/theme";

export function useThemeMode() {
  const globalStore = useGlobalStore();

  // 系统主题监听器
  const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");

  const handleSystemThemeChange = (e: MediaQueryListEvent | MediaQueryList) => {
    // 只有在当前模式是 'system' 时，才根据系统主题更新 DOM
    if (globalStore.themeMode === "system") {
      const isSystemDark = e.matches;
      // 这里不直接修改 globalStore.themeMode，而是根据 isSystemDark 决定 DOM 类
      // updateElementPlusTheme 内部可能需要这个布尔值
      // 直接同步到 DOM，或者让 syncToDOM 接收参数决定是否添加 dark 类
      const html = document.documentElement;
      const body = document.body;
      if (isSystemDark) {
        html.classList.add("dark");
        body.classList.add("dark");
      } else {
        html.classList.remove("dark");
        body.classList.remove("dark");
      }
    }
  };

  // 同步状态到 DOM 类名
  const syncToDOM = () => {
    const html = document.documentElement;
    const body = document.body;

    // 移除所有旧类，包括 dark，因为 dark 现在由 themeMode 统一控制
    html.classList.remove("dark", "color-weak", "gray-scale");
    body.classList.remove("dark", "color-weak", "gray-scale");

    // 根据新的 themeMode 添加 dark 类
    if (globalStore.themeMode === "dark" || (globalStore.themeMode === "system" && mediaQuery.matches)) {
      html.classList.add("dark");
      body.classList.add("dark");
    }

    // 添加色弱和灰度类（这部分不变）
    if (globalStore.isWeak) {
      html.classList.add("color-weak");
      body.classList.add("color-weak");
    }
    if (globalStore.isGrey) {
      html.classList.add("gray-scale");
      body.classList.add("gray-scale");
    }

    // 持久化保存状态到 localStorage
    localStorage.setItem(
      "themeSettings",
      JSON.stringify({
        themeMode: globalStore.themeMode, // 保存新的 themeMode
        isWeak: globalStore.isWeak,
        isGrey: globalStore.isGrey
      })
    );
  };

  /**
   * 设置主题颜色
   * @param type 类型
   * @param color 颜色
   */
  const setThemeColor = (type: string, color: string) => {
    updateElementPlusTheme(type, color);
  };

  // 初始化加载状态
  onMounted(() => {
    const saved = localStorage.getItem("themeSettings");
    if (saved) {
      const { themeMode, isWeak, isGrey } = JSON.parse(saved);
      globalStore.setGlobalState("themeMode", themeMode); // 设置新的 themeMode
      globalStore.setGlobalState("isWeak", isWeak);
      globalStore.setGlobalState("isGrey", isGrey);
    }

    // 系统主题初始判断：监听器保持，但只在 themeMode 为 'system' 时更新 DOM
    // 确保一开始就设置 DOM class
    syncToDOM(); // 初始渲染时同步一次 DOM

    // 监听系统主题变更（只需要监听一次）
    mediaQuery.addEventListener("change", handleSystemThemeChange);

    // 同步状态到 DOM
    syncToDOM();
  });

  // 监听状态变化并更新 DOM
  watch(
    () => [globalStore.themeMode, globalStore.isWeak, globalStore.isGrey], // 监听 themeMode
    () => {
      syncToDOM(); // 任何相关状态变化都同步 DOM
    }
  );

  // 自定义主题颜色
  watch(
    () => globalStore.primary,
    newPrimaryColor => {
      setThemeColor("primary", newPrimaryColor);
    },
    { immediate: true }
  );

  return {
    // 简化切换方法
    toggleDark: () => globalStore.setGlobalState("themeMode", globalStore.themeMode === "dark" ? "light" : "dark"),
    toggleGray: () => globalStore.setGlobalState("isGrey", !globalStore.isGrey),
    toggleWeak: () => globalStore.setGlobalState("isWeak", !globalStore.isWeak),

    // 对外暴露计算属性，方便组件使用
    currentThemeMode: computed(() => globalStore.themeMode),
    isDark: computed(() => globalStore.themeMode === "dark" || (globalStore.themeMode === "system" && mediaQuery.matches)), // 实际的暗黑模式状态
    isGray: computed(() => globalStore.isGrey),
    isWeak: computed(() => globalStore.isWeak),
    isFollowSystem: computed(() => globalStore.themeMode === "system") // 派生出跟随系统状态
  };
}

export enum ElementPlusModifyEnum {
  PRIMARY = "primary",
  SUCCESS = "success",
  WARNING = "warning",
  DANGER = "danger",
  INFO = "info"
}
